define(['model', 'utils'],function(model, utils) {
    console.log("presenter loaded");
    
    var addNewLocation = function(isLivingInChina, geolocation, callback) {
        var locationTrack = new model.LocationTrack();
        var onAddNewLocationCompleted = function(resultCode) {
            callback(resultCode);
        };

        locationTrack.add(isLivingInChina, geolocation, onAddNewLocationCompleted);
    };    

    return {
        getCurrentHomeEnvironmentData: function(callback) {
            var homeData = new model.CurrentHomeEnvironmentData();
            var onLoadHomeData = function (dataList) {
                var data = dataList[0];
                callback(data);
            };

            homeData.load(onLoadHomeData);
        },

        getHouseworkListByUser: function(user, callback) {
            var housework = new model.Housework();
            var onLoadHouseworkList = function (dataList) {
                callback(dataList);
            };

            housework.load(user, onLoadHouseworkList);
        }, 

        getUserList: function(callback) {
            var user = new model.User();
            var onLoadUserList = function (dataList) {
                callback(dataList);
            };

            user.load(onLoadUserList);
        },

        userLogin: function(username, password, callback) {
            var user = new model.User();
            var onLoginOperationCompleted = function (result) {
                callback(result);
            };

            user.login(username, password,  onLoginOperationCompleted);
        },

        addNewUser: function(username, role, callback) {
            var user = new model.User();
            var onAddNewUserCompleted = function (result) {
                callback(result.resultCode);
            };

            user.add(username, role, onAddNewUserCompleted);
        },

        updateUserPassword: function(currentPassword, newPassword, callback) {
            var user = new model.User();
            var onUpdateUserPasswordCompleted = function(resultCode) {
                callback(resultCode);
            };

            user.editPassword(currentPassword, newPassword, onUpdateUserPasswordCompleted);
        },

        removeUser: function(id, callback) {
            var user = new model.User();
            var onRemoveUserCompleted = function(resultCode) {
                callback(resultCode);
            };

            user.remove(id, onRemoveUserCompleted);
        },

        resetUserPassword: function(id, callback) {
            var user = new model.User();
            var onResetUserPasswordCompleted = function(resultCode) {
                callback(resultCode);
            };

            user.resetPassword(id, onResetUserPasswordCompleted);
        },

        markTaskCompleted: function(housework_id, callback) {
            var housework = new model.Housework();
            var onMarkCompleted = function (resultCode) {
                callback(resultCode);
            };

            housework.update(housework_id, onMarkCompleted);
        },

        addNewTask: function(user, task, reward, callback) {
            var housework = new model.Housework();
            var onAddNewTaskCompleted = function (resultCode) {
                callback(resultCode);
            };

            housework.add(user, task, reward, onAddNewTaskCompleted);
        },

        getTodayTemperatureList: function(type, callback) {
            var temperature = new model.Temperature();
            var onLoadTemperatureList = function (dataList) {
                callback(dataList);
            };

            temperature.load(type, onLoadTemperatureList);
        },

        getAbnormalBrightnessList: function(callback) {
            var record = new model.AlertRecord();
            var onLoadAlertRecordList = function (dataList) {
                callback(dataList);
            };

            record.load(1, onLoadAlertRecordList);
        },

        getAbnormalFiresafetyList: function(callback) {
            var record = new model.AlertRecord();
            var onLoadAlertRecordList = function (dataList) {
                callback(dataList);
            };

            record.load(2, onLoadAlertRecordList);
        },

        getBloodSugarListByUser: function(callback) {
            var sugar = new model.BloodSugar();
            var onLoadBloodSugarList = function (dataList) {
                callback(dataList);
            };

            sugar.load(onLoadBloodSugarList);
        },

        getBloodSugarStatsInToday: function(callback) {
            var sugar = new model.BloodSugar();
            var onGotBloodSugarStats = function (dataList) {
                callback(dataList);
            };

            sugar.statsInToday(onGotBloodSugarStats);
        },

        createNewSugarItem: function(date, time, tag, value, callback) {
            var sugar = new model.BloodSugar(); 
            var onCreatedNewSugarCompleted = function (resultCode) {
                callback(resultCode);
            };

            sugar.create(date, time, tag, value, onCreatedNewSugarCompleted);
        },

        getAllUsersLocationRecordList: function(callback) {
            var locationRecord = new model.LocationTrack();
            var onLoadLocationRecords = function (dataList) {
                callback(dataList);
            };

            locationRecord.allUsersRecords(onLoadLocationRecords);
        },

        getLocationRecordListForUser: function(user_id, callback) {
            var locationRecord = new model.LocationTrack();
            var onLoadLocationRecordListCompleted = function (dataList) {
                callback(dataList);
            };

            locationRecord.load(user_id, onLoadLocationRecordListCompleted);
        },

        getFileList: function(path, callback) {
            var myFile = new model.MyFile();
            var onLoadFileListCompleted = function (dataList) {
                callback(dataList);
            };

            myFile.loadList(path, onLoadFileListCompleted);
        },

        downloadMyFile: function(path, dest, successCallback, errorCallback) {
            var url = utils.appConfig().serverHost() + "/" + utils.appConfig().projectName + "/myfiles/show?path=" + path;

            utils.downloadFile(url, dest, successCallback, errorCallback);
        },

        uploadMyFile: function(path, successCallback, errorCallback) {
            var url = utils.appConfig().serverHost() + "/" + utils.appConfig().projectName + "/myfiles/new";
            var reqParamsMap = {};

            reqParamsMap.path = path;
            
            utils.uploadFile(url, reqParamsMap, 'allmedia', successCallback, errorCallback);
        },

        createNewFolder: function(path, folderName, callback) {
            var myFile = new model.MyFile();
            var onNewFolderCreationCompleted = function (resultCode) {
                callback(resultCode);
            };
            
            myFile.newFolder(path, folderName, onNewFolderCreationCompleted);
        },

        removeFile: function(path, filename, callback) {
            var myFile = new model.MyFile();
            var onRemoveFileCompleted = function (resultCode) {
                callback(resultCode);
            };

            myFile.remove(path + "/" + filename, onRemoveFileCompleted);
        },

        renameFile: function(path, oriFileName, newFileName, callback) {
            var myFile = new model.MyFile();
            var onRenameFileCompleted = function (resultCode) {
                callback(resultCode);
            };

            myFile.rename(path + "/" + oriFileName, path + "/" + newFileName, onRenameFileCompleted);
        },

        getAllContactsList: function(callback) {
            var onLoadContacsCompleted = function (contacts) {
                callback(contacts);
            };

            utils.searchContacts('', ['displayName'], onLoadContacsCompleted);
        },

        backupMyContacts: function(contacts, callback) {
            var myContact = new model.MyContact();
            var onBackupContactsCompleted = function (resultCode) {
                callback(resultCode);
            };

            myContact.backup(contacts, onBackupContactsCompleted);
        },

        syncMyContacts: function(successCallback) {
            var myContact = new model.MyContact();
            var onLoadContactsCompleted = function(dataList) {
                if (!window.isCordovaApp) {
                    console.log("Phonegap only feature. Aborted.");
                    return;
                }

                var rawContactsData = dataList[0].contacts;
                var rawContactsList = JSON.parse(rawContactsData);
                var contactsList = [];
                
                rawContactsList.forEach(function(element, index, array) {
                    var contact = navigator.contacts.create();
                    
                    contact.displayName = utils.ifNull(element.displayName, '');
                    //contact.id = utils.ifNull(element.id, '');
                    contact.nickname = utils.ifNull(element.nickname, '');
                    if (!utils.isObjEmpty(element.birthday)) {
                        contact.birthday = element.birthday;
                    }
                    contact.note = utils.ifNull(element.note, '');
                    
                    var name = new ContactName();
                    var elementName = element.name;
                    if (!utils.isObjEmpty(elementName)) {
                        name.givenName = utils.ifNull(elementName.givenName, '');
                        name.familyName = utils.ifNull(elementName.familyName, '');
                        name.formatted = utils.ifNull(elementName.formatted, '');
                        name.middleName = utils.ifNull(elementName.middleName, '');
                        name.honorificPrefix = utils.ifNull(elementName.honorificPrefix, '');
                        name.honorificSuffix = utils.ifNull(elementName.honorificSuffix, '');
                    }
                    contact.name = name;
                    
                    var phoneNumbers = [];
                    var elementPhoneNumbers = utils.ifNull(element.phoneNumbers, []);
                    elementPhoneNumbers.forEach(function(item, position) {
                        phoneNumbers.push(
                                new ContactField(
                                    utils.ifNull(item.type, ''),
                                    utils.ifNull(item.value, ''),
                                    utils.ifNull(item.pref, false)
                                )
                                );
                    });
                    contact.phoneNumbers = phoneNumbers;

                    var emails = [];
                    var elementEmails = utils.ifNull(element.emails, []);
                    elementEmails.forEach(function(item, position) {
                        emails.push(
                                new ContactField(
                                    utils.ifNull(item.type, ''),
                                    utils.ifNull(item.value, ''),
                                    utils.ifNull(item.pref, false)
                                )
                        );
                    });
                    contact.emails = emails;

                    var addresses = [];
                    var elementAddresses = utils.ifNull(element.addresses, []);
                    elementAddresses.forEach(function(item, position) {
                        var add = new ContactAddress();

                        add.pref = utils.ifNull(item.pref, false);
                        add.type = utils.ifNull(item.type, '');
                        add.formatted = utils.ifNull(item.formatted, '');
                        add.streetAddress = utils.ifNull(item.streetAddress, '');
                        add.locality = utils.ifNull(item.locality, '');
                        add.region = utils.ifNull(item.region, '');
                        add.postalCode = utils.ifNull(item.postalCode, '');
                        add.country = utils.ifNull(item.country, '');

                        addresses.push(add);
                    });
                    contact.addresses = addresses;
                    
                    var ims = [];
                    var elementIms = utils.ifNull(element.ims, []);
                    elementIms.forEach(function(item, position) {
                        ims.push(
                                new ContactField(
                                    utils.ifNull(item.type, ''),
                                    utils.ifNull(item.value, ''),
                                    utils.ifNull(item.pref, false)
                                )
                        );
                    });
                    contact.ims = ims;

                    var organizations = [];
                    var elementOrganizations = utils.ifNull(element.organizations, []);
                    elementOrganizations.forEach(function(item, position) {
                        var org = new ContactOrganization();

                        org.pref = utils.ifNull(item.pref, '');
                        org.type = utils.ifNull(item.type, '');
                        org.name = utils.ifNull(item.name, '');
                        org.department = utils.ifNull(item.department, '');
                        org.title = utils.ifNull(item.title, '');

                        organizations.push(org);
                    });
                    contact.organizations = organizations;

                    var photos = [];
                    var elementPhotos = utils.ifNull(element.photos, []);
                    elementPhotos.forEach(function(item, position) {
                        photos.push(
                                new ContactField(
                                    utils.ifNull(item.type, ''),
                                    utils.ifNull(item.value, ''),
                                    utils.ifNull(item.pref, false)
                                )
                        );
                    });
                    contact.photos = photos;
                    
                    var categories = [];
                    var elementCategories = utils.ifNull(element.categories, []);
                    elementCategories.forEach(function(item, position) {
                        categories.push(
                                new ContactField(
                                    utils.ifNull(item.type, ''),
                                    utils.ifNull(item.value, ''),
                                    utils.ifNull(item.pref, false)
                                )
                        );
                    });
                    contact.categories = categories;

                    var urls = [];
                    var elementUrls = utils.ifNull(element.urls, []);
                    elementUrls.forEach(function(item, position) {
                        urls.push(
                                new ContactField(
                                    utils.ifNull(item.type, ''),
                                    utils.ifNull(item.value, ''),
                                    utils.ifNull(item.pref, false)
                                )
                        );
                    });
                    contact.urls = urls;

                    contactsList.push(contact);
                });
                
                var contactsCount = contactsList.length;
                var syncCallback = function () {
                    successCallback(contactsCount);
                };
                console.log("Going to save " + contactsCount + " contacts");
                utils.syncContacts(contactsList, syncCallback);
            };

            myContact.load(onLoadContactsCompleted);
        },

        reportMyLocation: function(isLivingInChina) {
            var onSuccess = function(position) {
                addNewLocation(
                                isLivingInChina, 
                                position.coords.latitude + "," + position.coords.longitude, 
                                function(resultCode) {
                                   if (1 === resultCode) 
                                       console.log("Send location record successfully.");
                                   else
                                       console.log("Failed to send location record.");
                                }
                              );
            };
            var onError = function(err) {
                alert("Unable to get your location: " + err.message);
            };
            var timeout = 60000;

            utils.getCurrentLocation(onSuccess, onError, timeout, isLivingInChina);
        },    

        updateUserOption: function(key, value, callback) {
            var option = new model.Option();
            var onOptionUpdateCompleted = function(resultCode) {
                callback(resultCode);
            };

            option.update(key, value, onOptionUpdateCompleted);
        },

        getUserOptions: function(callback) {
            var option = new model.Option();
            var onLoadOptionsCompleted = function(dataList) {
                callback(dataList);
            };

            option.load(onLoadOptionsCompleted);
        },

        getMyselfInfo: function(callback) {
            var me = new model.User();
            var onLoadMyselfInfoCompleted = function(dataList) {
                callback(dataList);
            };

            me.loadMe(onLoadMyselfInfoCompleted);
        },

        updateMyselfInfo: function(field, value, callback) {
            var me = new model.User();
            var onUpdateMyselfInfoCompleted = function(resultCode) {
                callback(resultCode);
            };

            var fieldsToEditMap = {};

            fieldsToEditMap[field] = value;

            me.update(JSON.stringify(fieldsToEditMap), onUpdateMyselfInfoCompleted);
        },

        updateMyAvatar: function(updateSuccessCallback, updateFailureCallback) {
            var me = new model.User();
            var reqParamsMap = {};
            var url = utils.appConfig().serverHost() + "/" + utils.appConfig().projectName + "/user/photo/edit";
            
            utils.uploadFile(url, reqParamsMap, 'picture', updateSuccessCallback, updateFailureCallback);
        },
        
        sendAppToBackground: function(successCallback, errorCallback) {
            utils.sendAppToBackground(successCallback, errorCallback);
        },

        sendStatusBarNotification: function(title, text, ticker, enableExtraEffects, successCallback, errorCallback) {
            utils.sendNotify(title, text, ticker, enableExtraEffects, successCallback, errorCallback);
        },
        
        exitApp: function() {
            utils.exitApp();
        },    
    };
});
